#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct String
{
	int len;
	char* data;
}String;
String* initString()
{
	String* s = (String*)malloc(sizeof(String));
	assert(s);
	s->data = NULL;
	s->len = 0;
	return s;
}
void stringAssign(String* s,const char* data)
{
	s->data = NULL;
	int len=0;
	const char* temp = data;
	while (*data)
	{
		len++;
		data++;
	}
	s->data = (char*)malloc(sizeof(char)*(len+1));
	assert(s->data);
	for (int i = 0; i < len; i++)
	{
		s->data[i] = *temp;
		temp++;
	}
	s->len = len;
}
void printString(String* s)
{
	for (int i = 0; i < s->len; i++)
		printf(i == 0 ? "%c" : "->%c", s->data[i]);
	printf("\n");
}

int* getNext(String* s)
{
	int* next = (int*)malloc(sizeof(int)*s->len);
	assert(next);
	int i = 0;
	int j = -1;
	next[i] = j;
	while (i < s->len - 1)
	{
		if (j == -1 || s->data[i] == s->data[j])
		{
			i++;
			j++;
			next[i] = j;
		}
		else
		{
			j = next[j];
		}
	}
	return next;
}
void printNext(int* next, int len)
{
	for (int i = 0; i < len; i++)
		printf(i == 0 ? "%d" : "->%d", next[i]);
	printf("\n");
}
void kmpMatch(String* dest, String* src, int* next)
{
	int i = 0, j = 0;
	while (i < dest->len && j < src->len)
	{
		if (j==-1||dest->data[i] == src->data[j])
		{
			i++;
			j++;
		}
		else
			j = next[j];
	}
	if (j == src->len)
		printf("kmp success");
	else
		printf("kmp fail");
}
int main()
{
	String* s = initString();
	String* s1 = initString();
	stringAssign(s, "apple");
	stringAssign(s1, "ea");
	int* next = getNext(s);
	printString(s);
	printNext(next, s->len);
	printString(s1);
	printNext(next, s1->len);
	kmpMatch(s, s1, next);
	return 0;
}